package com.zone.infrastructure.persistent.repository;

import com.google.gson.Gson;
import com.zone.domain.task.model.entity.TaskEntity;
import com.zone.domain.task.model.valobj.TaskState;
import com.zone.domain.task.repository.ITaskRepository;
import com.zone.infrastructure.event.MessageProduct;
import com.zone.infrastructure.persistent.dao.ITaskDao;
import com.zone.infrastructure.persistent.po.Task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/2/24
 */
@Slf4j
@Repository
public class TaskRepository implements ITaskRepository {
    @Autowired
    private ITaskDao taskDao;
    @Autowired
    private MessageProduct messageProduct;

    @Override
    public List<TaskEntity> queryNoSendTaskList() {
        List<Task> taskList = taskDao.queryNoSendTaskList();
        return taskList.stream()
                .map(task -> {
                    TaskEntity taskEntity = new TaskEntity();
                    taskEntity.setUserId(task.getUserId());
                    taskEntity.setTopic(task.getTopic());
                    taskEntity.setMessageId(task.getMessageId());
                    taskEntity.setMessage(task.getMessage());
                    taskEntity.setState(TaskState.valueOf(task.getState()));
                    return taskEntity;
                }).collect(Collectors.toList());
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        // 发送mq
        Gson gson = new Gson();
        Object event = gson.fromJson(taskEntity.getMessage(), Object.class);
        messageProduct.sendMessage(taskEntity.getTopic(), event);
    }

    public void updateCompleteByUserIdAndMessageId(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        task.setState(TaskState.COMPLETED.getCode());
        taskDao.updateStateByMessageId(task);
    }

    public void updateFailByUserIdAndMessageId(String userId, String messageId) {
        Task task = new Task();
        task.setUserId(userId);
        task.setMessageId(messageId);
        task.setState(TaskState.FAIL.getCode());
        taskDao.updateStateByMessageId(task);
    }
}
